package py.owner.log.format;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;

public class KVJsonFormat extends AbstractLogFormat {

    /**
     * log map
     */
    private Map<String, Object> map = new HashMap<>();
    private static final String JSON_FORMAT = "mapJson:";

    private KVJsonFormat(String title) {
        super(title);
    }

    public static KVJsonFormat title(String title) {
        return new KVJsonFormat(title);
    }

    /**
     * 添加日志
     * @param key
     * @param v
     * @return
     */
    public KVJsonFormat add(String key, Object v) {
        map.put(key, v);
        return this;
    }

    /**
     * 添加map类型日志
     * @param params
     * @return
     */
    public KVJsonFormat addAll(Map<String, Object> params) {
        if (params != null) {
            this.map.putAll(params);
        }
        return this;
    }

    @Override
    protected String buildLogMsg() {
        return format(map);
    }

    /**
     * format log
     * @param obj
     * @return
     */
    private String format(Object obj) {
        return JSON_FORMAT + (obj == null ? "{}" : JSON.toJSONString(obj));
    }
}
